from rest_framework import serializers
from .models import Environment, HostType, HostGroup, Host


class EnvironmentSerializer(serializers.ModelSerializer):
    """环境序列化器"""
    host_count = serializers.SerializerMethodField()

    class Meta:
        model = Environment
        fields = '__all__'

    def get_host_count(self, obj):
        """获取环境下的主机数量"""
        return obj.host_set.filter(is_active=True).count()


class HostTypeSerializer(serializers.ModelSerializer):
    """主机类型序列化器"""
    host_count = serializers.ReadOnlyField()

    class Meta:
        model = HostType
        fields = '__all__'


class HostGroupSerializer(serializers.ModelSerializer):
    """主机组序列化器"""
    environment_name = serializers.CharField(source='environment.name', read_only=True)
    host_count = serializers.ReadOnlyField()

    class Meta:
        model = HostGroup
        fields = '__all__'

    def to_representation(self, instance):
        """自定义序列化输出"""
        data = super().to_representation(instance)
        # 添加负载均衡配置
        data['loadBalancer'] = {
            'enabled': instance.load_balancer_enabled,
            'algorithm': instance.load_balancer_algorithm,
            'port': instance.load_balancer_port
        }
        # 添加健康检查配置
        data['healthCheck'] = {
            'enabled': instance.health_check_enabled,
            'interval': instance.health_check_interval,
            'timeout': instance.health_check_timeout,
            'failureThreshold': instance.health_check_failure_threshold,
            'path': instance.health_check_path
        }
        return data

    def create(self, validated_data):
        """创建主机组"""
        # 处理嵌套的负载均衡和健康检查配置
        load_balancer = self.initial_data.get('loadBalancer', {})
        health_check = self.initial_data.get('healthCheck', {})
        
        if load_balancer:
            validated_data['load_balancer_enabled'] = load_balancer.get('enabled', False)
            validated_data['load_balancer_algorithm'] = load_balancer.get('algorithm', 'round_robin')
            validated_data['load_balancer_port'] = load_balancer.get('port', 80)
        
        if health_check:
            validated_data['health_check_enabled'] = health_check.get('enabled', False)
            validated_data['health_check_interval'] = health_check.get('interval', 30)
            validated_data['health_check_timeout'] = health_check.get('timeout', 5)
            validated_data['health_check_failure_threshold'] = health_check.get('failureThreshold', 3)
            validated_data['health_check_path'] = health_check.get('path', '/health')
        
        return super().create(validated_data)

    def update(self, instance, validated_data):
        """更新主机组"""
        # 处理嵌套的负载均衡和健康检查配置
        load_balancer = self.initial_data.get('loadBalancer', {})
        health_check = self.initial_data.get('healthCheck', {})
        
        if load_balancer:
            validated_data['load_balancer_enabled'] = load_balancer.get('enabled', instance.load_balancer_enabled)
            validated_data['load_balancer_algorithm'] = load_balancer.get('algorithm', instance.load_balancer_algorithm)
            validated_data['load_balancer_port'] = load_balancer.get('port', instance.load_balancer_port)
        
        if health_check:
            validated_data['health_check_enabled'] = health_check.get('enabled', instance.health_check_enabled)
            validated_data['health_check_interval'] = health_check.get('interval', instance.health_check_interval)
            validated_data['health_check_timeout'] = health_check.get('timeout', instance.health_check_timeout)
            validated_data['health_check_failure_threshold'] = health_check.get('failureThreshold', instance.health_check_failure_threshold)
            validated_data['health_check_path'] = health_check.get('path', instance.health_check_path)
        
        return super().update(instance, validated_data)


class HostSerializer(serializers.ModelSerializer):
    """主机序列化器"""
    host_type_name = serializers.CharField(source='host_type.name', read_only=True)
    environment_name = serializers.CharField(source='environment.name', read_only=True)
    host_group_name = serializers.CharField(source='host_group.name', read_only=True)
    owner_name = serializers.CharField(source='owner.username', read_only=True)
    
    # 连接信息（写入时使用）
    ssh_password_plain = serializers.CharField(write_only=True, required=False, allow_blank=True)
    ssh_private_key_plain = serializers.CharField(write_only=True, required=False, allow_blank=True)

    class Meta:
        model = Host
        fields = '__all__'
        extra_kwargs = {
            'ssh_password': {'write_only': True},
            'ssh_private_key': {'write_only': True},
        }

    def to_representation(self, instance):
        """自定义序列化输出"""
        data = super().to_representation(instance)
        
        # 添加硬件配置信息
        data['specs'] = {
            'cpu': instance.cpu_cores,
            'memory': instance.memory_gb,
            'disk': instance.disk_gb
        }
        
        # 添加连接信息（不包含敏感数据）
        data['connection'] = {
            'sshPort': instance.ssh_port,
            'username': instance.ssh_username,
            'authType': instance.ssh_auth_type
        }
        
        # 移除敏感字段
        data.pop('ssh_password', None)
        data.pop('ssh_private_key', None)
        
        return data

    def create(self, validated_data):
        """创建主机"""
        # 处理密码加密
        password_plain = validated_data.pop('ssh_password_plain', None)
        private_key_plain = validated_data.pop('ssh_private_key_plain', None)
        
        # 处理嵌套的配置信息
        specs = self.initial_data.get('specs', {})
        connection = self.initial_data.get('connection', {})
        
        if specs:
            validated_data['cpu_cores'] = specs.get('cpu', 2)
            validated_data['memory_gb'] = specs.get('memory', 4)
            validated_data['disk_gb'] = specs.get('disk', 100)
        
        if connection:
            validated_data['ssh_port'] = connection.get('sshPort', 22)
            validated_data['ssh_username'] = connection.get('username', 'root')
            validated_data['ssh_auth_type'] = connection.get('authType', 'password')
        
        instance = super().create(validated_data)
        
        # 加密存储敏感信息
        if password_plain:
            instance.ssh_password = instance.encrypt_password(password_plain)
        if private_key_plain:
            instance.ssh_private_key = instance.encrypt_private_key(private_key_plain)
        
        instance.save()
        return instance

    def update(self, instance, validated_data):
        """更新主机"""
        # 处理密码加密
        password_plain = validated_data.pop('ssh_password_plain', None)
        private_key_plain = validated_data.pop('ssh_private_key_plain', None)
        
        # 处理嵌套的配置信息
        specs = self.initial_data.get('specs', {})
        connection = self.initial_data.get('connection', {})
        
        if specs:
            validated_data['cpu_cores'] = specs.get('cpu', instance.cpu_cores)
            validated_data['memory_gb'] = specs.get('memory', instance.memory_gb)
            validated_data['disk_gb'] = specs.get('disk', instance.disk_gb)
        
        if connection:
            validated_data['ssh_port'] = connection.get('sshPort', instance.ssh_port)
            validated_data['ssh_username'] = connection.get('username', instance.ssh_username)
            validated_data['ssh_auth_type'] = connection.get('authType', instance.ssh_auth_type)
        
        instance = super().update(instance, validated_data)
        
        # 更新敏感信息
        if password_plain:
            instance.ssh_password = instance.encrypt_password(password_plain)
        if private_key_plain:
            instance.ssh_private_key = instance.encrypt_private_key(private_key_plain)
        
        instance.save()
        return instance


class HostListSerializer(serializers.ModelSerializer):
    """主机列表序列化器（简化版）"""
    host_type_name = serializers.CharField(source='host_type.name', read_only=True)
    environment_name = serializers.CharField(source='environment.name', read_only=True)
    host_group_name = serializers.CharField(source='host_group.name', read_only=True)
    
    class Meta:
        model = Host
        fields = [
            'id', 'hostname', 'ip', 'host_type', 'host_type_name',
            'environment', 'environment_name', 'host_group', 'host_group_name',
            'status', 'last_heartbeat', 'cpu_cores', 'memory_gb', 'disk_gb',
            'is_active', 'created_at'
        ]


class HostConnectionTestSerializer(serializers.Serializer):
    """主机连接测试序列化器"""
    host_id = serializers.IntegerField()
    test_type = serializers.ChoiceField(choices=['ping', 'ssh', 'all'], default='all')
    
    def validate_host_id(self, value):
        """验证主机ID"""
        try:
            Host.objects.get(id=value, is_active=True)
        except Host.DoesNotExist:
            raise serializers.ValidationError("主机不存在或已禁用")
        return value


class HostBatchOperationSerializer(serializers.Serializer):
    """主机批量操作序列化器"""
    host_ids = serializers.ListField(child=serializers.IntegerField())
    operation = serializers.ChoiceField(choices=['enable', 'disable', 'delete', 'update_group'])
    parameters = serializers.DictField(required=False)
    
    def validate_host_ids(self, value):
        """验证主机ID列表"""
        if not value:
            raise serializers.ValidationError("主机ID列表不能为空")
        
        existing_ids = Host.objects.filter(id__in=value).values_list('id', flat=True)
        missing_ids = set(value) - set(existing_ids)
        if missing_ids:
            raise serializers.ValidationError(f"以下主机ID不存在: {list(missing_ids)}")
        
        return value
